package cn.lysj.framework.verify.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);


    public static String sendJsonPost(String url, String paramJson) {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse httpresponse = null;
        String response = "";
        try {
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringentity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
            System.out.println("post内容"+stringentity.toString());
            httpPost.setEntity(stringentity);
            httpresponse = httpclient.execute(httpPost);
            response = EntityUtils.toString(httpresponse.getEntity(),"utf-8");
            logger.info("response: " + response);
            return response;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return response;
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpresponse != null) {
                try {
                    httpresponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
